package com.motorhome.api.service.impl;

import com.motorhome.api.common.statics.ApiStatics;
import com.motorhome.api.dao.DeviceDao;
import com.motorhome.api.domain.*;
import com.motorhome.api.service.DeviceApiService;
import com.motorhome.base.cache.MemcachedCache;
import com.motorhome.base.dao.Pager;
import com.motorhome.base.util.HttpClientUtil;
import com.motorhome.base.util.JsonUtil;
import com.motorhome.base.util.Result;
import com.motorhome.base.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: John
 */
@Service
public class DeviceApiServiceImpl implements DeviceApiService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private MemcachedCache cache;

    /**
     * 用户登录获取令牌
     *
     * @return
     */
    @Override
    public String getAccessToken() {

        String accessToken = (String)cache.get(ApiStatics.DEVICE_ACCESSTOKEN_KEY);
        if (accessToken != null) {
            return accessToken;
        }

        Map<String, Object> params = new HashMap<>();
        params.put("UserName", ApiStatics.DEVICE_USERNAME);
        params.put("Password", ApiStatics.DEVICE_PASSWORD);

        logger.info(ApiStatics.DEVICE_USERNAME);

        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("jsondata", JsonUtil.toJson(params));

        String result = new HttpClientUtil().post(ApiStatics.DEVICE_LOGIN_URL, jsonData);
        if (result != null) {
            DeviceLoginResult deviceLoginResult = JsonUtil.fromJson(result, DeviceLoginResult.class);
            if (deviceLoginResult != null && deviceLoginResult.getResultCode() == 0) {
                accessToken = deviceLoginResult.getResult().getAccessToken();
                if (accessToken != null) {
                    cache.set(ApiStatics.DEVICE_ACCESSTOKEN_KEY, accessToken, "7d");
                    return accessToken;
                }
            }
        }
        return null;
    }

    /**
     * 获取设备最新定位
     *
     * @param deviceNumber 设备编号
     * @param coorType     坐标类型，
     *                     0：GPS坐标
     *                     1：百度坐标
     *                     2：谷歌坐标
     * @return
     */
    @Override
    public DevicePositionResult getDevicePosition(String deviceNumber, int coorType) {
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", getAccessToken());
        params.put("DeviceNumber", deviceNumber);
        params.put("CoorType", coorType);

        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("jsondata", JsonUtil.toJson(params));

        String result = new HttpClientUtil().post(ApiStatics.DEVICE_POSITION_URL, jsonData);
        if (result != null) {
            return JsonUtil.fromJson(result, DevicePositionResult.class);
        }
        return null;
    }

    @Override
    public Result getDevicePositionOther(String deviceNumber, int coorType) {
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", getAccessToken());
        params.put("DeviceNumber", deviceNumber);
//        params.put("CoorType", coorType);



        DWRet ret = deviceDao.getDW(deviceNumber);


        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("lat", ret.latitude);
        jsonData.put("lon", ret.longitude);


       return  new Result(0, "成功", jsonData);
//        String result = new HttpClientUtil().post(ApiStatics.DEVICE_POSITION_URL, jsonData);
////        if (result != null) {
//            return JsonUtil.fromJson(result, DevicePositionResult.class);
//        }
//        return null;
    }


    /**
     * 获取设备列表最新定位
     *
     * @param coorType    坐标类型，
     *                    0：GPS坐标
     *                    1：百度坐标
     *                    2：谷歌坐标
     * @param pageIndex   页号（页号从1开始）
     * @param pageCount   每页数目（最大数目不超过500）
     * @return
     */
    @Override
    public DevicePositionListResult getDeviceListPosition(int coorType, int pageIndex, int pageCount) {
        Map<String, Object> params = new HashMap<>();
        params.put("access_token", getAccessToken());
        params.put("CoorType", coorType);
        params.put("PageIndex", pageIndex);
        params.put("PageCount", pageCount);

        Map<String, Object> jsonData = new HashMap<>();
        jsonData.put("jsondata", JsonUtil.toJson(params));

        String result = new HttpClientUtil().post(ApiStatics.DEVICE_LIST_POSITION_URL, jsonData);
        if (result != null) {
            return JsonUtil.fromJson(result, DevicePositionListResult.class);
        }
        return null;
    }

}
